﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CoolCode.Entities;
using CoolCode.Services;

namespace CoolCode.Web.UI.Views.Check
{
    public partial class CreateProduct :AuthPage
    {
        private IInspectionService _Service;
        public IInspectionService Service
        {
            get
            {
                if (_Service == null)
                {
                    _Service = ServiceFactory.Produce<IInspectionService>();
                }
                return _Service;
            }
        }

        private int _key = 0;
        public int Key
        {
            get
            {
                if (_key == 0)
                {
                    _key = RequestUtility.GetQueryString("key", -1);
                }
                return _key;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            btnSave.Click += new EventHandler(btnSave_Click);

            if (!IsPostBack)
            {
                Inspection entity;
                if (Key != -1)
                {
                    entity = Service.Get(Key);
                }
                else
                {
                    entity = new Inspection();
                    entity.CheckDate = DateTime.Now;
                }
                pnlEntry.UpdatePage(entity);
            }
            var rs = this.FindControls<RequiredFieldValidator>();
            foreach (var r in rs)
            {
                r.ErrorMessage = "*";
                r.ToolTip = "不能为空";
            }

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Inspection model = new Inspection();
            this.UpdateModel(model);

            string message;
            if (!Validate(model, out message))
            {
                udpEntry.Alert(message);
                return;
            }

            model.CreateDate = DateTime.Now;
            model.UpdateDate = DateTime.Now;
            model.CreateUser = User.Identity.Name;
            model.UpdateUser = User.Identity.Name;
            model.Status = ProductStatus.In.GetAttachedString();
            model.CheckDate = model.CheckDate.Markup();
            Service.SaveInspection(model, null);
            
            ITipsService tipsService = ServiceFactory.Produce<ITipsService>();
            Enum<TipsType>.Foreach(tipsType =>
            {
                var tips = new Tips
                {
                    Type = tipsType.GetAttachedString(),
                    Text = getTextByType(model, tipsType), // model.ProductSpec,
                    CreateUser = User.Identity.Name,
                    CreateDate = DateTime.Now,
                    UpdateUser = User.Identity.Name,
                    UpdateDate = DateTime.Now,
                    Value = string.Empty,
                    Times = 1,
                    Status = "1",
                };
                tipsService.SaveTips(tips);
            });

            Inspection entity = new Inspection();
            entity.CheckDate = DateTime.Now;
            pnlEntry.UpdatePage(entity);
            cdrCheckDate.Value = DateTime.Now;
            udpEntry.Update();
            if (Key == -1)
            {
                udpEntry.Alert("保存成功！");
            }
            else
            {
                //Response.Redirect("~");
                this.View<Products>();
            }
            //AjaxControlToolkit.ToolkitScriptManager.RegisterClientScriptBlock(udpEntry, udpEntry.GetType(),"Message",
            //    " alert('保存成功！'); ", true);
            //Response.Write("<script>alert('保存成功！');</script>");
            //this.View<Products>();
        }

        private bool Validate(Inspection model, out string message)
        {
            message =null;
            string queryProductID = RequestUtility.GetQueryString("product");
            bool checkProductID = Key == -1 || queryProductID != txtProductID.Text;
            Inspection originalProduct = null;

            if (checkProductID )
            {
                originalProduct = Service.Get(model.ProductID);
                if (originalProduct != null)
                {
                    message="数据库已经存在此产品：" + model.ProductID;
                    return false;
                }
            }

            if (!Validate("胶面外径（远）", model.ODFar, out message))
            { 
                return false;
            }
            if (!Validate("胶面外径（近）", model.ODClose, out message))
            {
                return false;
            }
            if (!Validate("锥体高度", model.ConeHeight, out message))
            {
                return false;
            }
            if (!Validate("球囊长度", model.SacculusLength, out message))
            {
                return false;
            }
            if (!Validate("球囊伸长长度", model.SacculusStretch, out message))
            {
                return false;
            }
            if (!Validate("220KPa压力测试（外径1）", model.ODStressTest1, out message))
            {
                return false;
            }
            if (!Validate("220KPa压力测试（外径2）", model.ODStressTest2, out message))
            {
                return false;
            }
            if (!Validate("220KPa压力测试（外径/长度）", model.StressTestLength, out message))
            {
                return false;
            } 
            return true;
        }

        private bool Validate(string property, decimal value,  out string message)
        {
            decimal maxDbNum = 9999.99m;
            string overflowMsg = "{0}的有效范围是：{1} ~ {2}";
            if (value > maxDbNum || value < -maxDbNum )
            {
                message = string.Format(overflowMsg, property, -maxDbNum, maxDbNum);
                return false;
            }
            message = null;
            return true;
        }

        private Func<Inspection, TipsType, string> getTextByType = (p, type) =>
        {
            switch (type)
            {
                case TipsType.Appearance:
                    return p.Appearance;
                case TipsType.Burse:
                    return p.Burse;
                case TipsType.Checker:
                    return p.Checker;
                case TipsType.Degumming:
                    return p.Degumming;
                case TipsType.Drawback:
                    return p.Drawback;
                case TipsType.Face:
                    return p.Face;
                case TipsType.Interlayer:
                    return p.Interlayer;
                case TipsType.ProductSpec:
                    return p.ProductSpec;
                default:
                    return string.Empty;
            }
        };
    }
}
